package com.explment.lens.exception;

import com.explment.lens.utils.result.ResultCode;
import com.explment.lens.utils.result.ResultData;
import org.springframework.http.HttpStatus;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Map;
import java.util.stream.Collectors;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ResultData handleException(Exception e) {
        e.printStackTrace();
        return ResultData.fail(ResultCode.INTERNAL_ERROR, e.getMessage());
    }

    @ExceptionHandler(BusinessException.class)
    public ResultData handleBusinessException(BusinessException ex) {
        ex.printStackTrace();
        return ResultData.fail(ex.getCode(), ex.getMessage());
    }

    @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
    public ResultData handleUnsupportedMediaType(HttpMediaTypeNotSupportedException ex) {
        String message = "Unsupported Content-Type. Please use 'application/json'.";
        return ResultData.fail(ResultCode.BAD_REQUEST, message);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultData handleValidation(MethodArgumentNotValidException ex) {
        Map<String, String> errors = ex.getBindingResult()
                .getFieldErrors()
                .stream()
                .collect(Collectors.toMap(
                        fieldError -> fieldError.getField(),
                        fieldError -> fieldError.getDefaultMessage() != null ?
                                fieldError.getDefaultMessage() : ""));
        return ResultData.fail(ResultCode.BAD_REQUEST);
    }
}

